<template>
  <div class="zone-management-container">
    <!-- 社区信息栏 -->
    <div class="community-info-bar" v-if="communityInfo">
      <el-card class="community-card" shadow="never">
        <div class="community-info">
          <div class="community-name">
            <el-icon><Location /></el-icon>
            <span class="name-text">{{ communityInfo.communityName }}</span>
          </div>
          <div class="community-address">
            <el-icon><MapLocation /></el-icon>
            <div class="address-details">
              <!-- 省市区街道信息 -->
              <div class="region-path" v-if="regionPathInfo.fullPath">
                <span class="region-item" v-if="regionPathInfo.province">{{ regionPathInfo.province }}</span>
                <span class="region-separator" v-if="regionPathInfo.province && regionPathInfo.city">·</span>
                <span class="region-item" v-if="regionPathInfo.city">{{ regionPathInfo.city }}</span>
                <span class="region-separator" v-if="regionPathInfo.city && regionPathInfo.district">·</span>
                <span class="region-item" v-if="regionPathInfo.district">{{ regionPathInfo.district }}</span>
                <span class="region-separator" v-if="regionPathInfo.district && regionPathInfo.street">·</span>
                <span class="region-item" v-if="regionPathInfo.street">{{ regionPathInfo.street }}</span>
              </div>
              <!-- 详细地址 -->
              <div class="detail-address" v-if="communityInfo.address">
                <span class="address-text">{{ communityInfo.address }}</span>
              </div>
            </div>
          </div>
          <!-- 操作模式指示器 -->
          <div class="operation-mode-indicator">
            <el-tag 
              :type="communityEntryState.operationMode === 'CREATE' ? 'primary' : 'success'"
              size="large"
            >
              <el-icon v-if="communityEntryState.operationMode === 'CREATE'"><Plus /></el-icon>
              <el-icon v-else><EditPen /></el-icon>
              {{ communityEntryState.operationMode === 'CREATE' ? '创建模式' : '编辑模式' }}
            </el-tag>
            <div class="mode-description">
              <span v-if="communityEntryState.isFirstEntry">
                首次进入，可以创建新分区
              </span>
              <span v-else>
                已有 {{ communityEntryState.zoneCount }} 个分区，可以编辑现有数据
              </span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分区管理主界面 -->
    <div class="zone-management-main">
      <div class="zone-layout">
        <!-- 左侧楼栋图标库 -->
        <div class="building-library">
          <el-card class="library-card" shadow="never">
            <template #header>
              <div class="card-header">
                <el-icon><House /></el-icon>
                <span>楼栋图标库</span>
              </div>
            </template>
            
            <div class="library-content">
              <!-- 楼栋列表 -->
              <div class="building-list">
                <div
                  v-for="building in filteredBuildings"
                  :key="building.id"
                  class="building-item"
                  :class="{ 'building-selected': selectedBuilding?.id === building.id }"
                  @click="selectBuilding(building)"
                  draggable="true"
                  @dragstart="handleDragStart($event, building)"
                >
                  <div class="building-icon">
                    <el-icon><House /></el-icon>
                  </div>
                  <div class="building-info">
                    <div class="building-name">{{ building.buildingName }}</div>
                    <div class="building-type">{{ building.buildingTypeName }}</div>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 中央绘图区域 -->
        <div class="drawing-area">
          <el-card class="drawing-card" shadow="never">
            <template #header>
              <div class="card-header">
                <el-icon><Grid /></el-icon>
                <span>分区绘图区域</span>
                <div class="toolbar">
                  <!-- 工具栏 -->
                  <div class="tool-group">
                    <el-button
                      :type="isSelectMode ? 'primary' : 'default'"
                      size="small"
                      @click="toggleSelectMode"
                    >
                      <el-icon><Pointer /></el-icon>
                      {{ isSelectMode ? '取消选择' : '选择' }}
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      :disabled="!selectedBuilding"
                      @click="deleteSelectedBuilding"
                    >
                      <el-icon><Delete /></el-icon>
                      删除楼栋
                    </el-button>
                  </div>
                  
                  <!-- 缩放控制 -->
                  <div class="zoom-controls">
                    <div class="zoom-group">
                      <span class="zoom-label">画布:</span>
                      <el-button size="small" @click="zoomOut">
                        <el-icon><ZoomOut /></el-icon>
                      </el-button>
                      <span class="zoom-level">{{ Math.round(zoomLevel * 100) }}%</span>
                      <el-button size="small" @click="zoomIn">
                        <el-icon><ZoomIn /></el-icon>
                      </el-button>
                    </div>
                  </div>
                  
                  <!-- 操作按钮 -->
                  <div class="action-buttons">
                    <el-button type="success" size="small" @click="saveZones" :loading="loading">
                      <el-icon><Check /></el-icon>
                      保存
                    </el-button>
                    <el-button type="warning" size="small" @click="undoLastOperation" :disabled="!canUndo">
                      <el-icon><RefreshLeft /></el-icon>
                      撤销
                    </el-button>
                    <el-button type="info" size="small" @click="redoLastOperation" :disabled="!canRedo">
                      <el-icon><RefreshRight /></el-icon>
                      重做
                    </el-button>
                  </div>
                </div>
              </div>
            </template>

            <!-- 绘图画布 -->
            <div class="canvas-container">
              <!-- 无绘图数据提示 -->
              <div v-if="!hasDrawingData" class="no-drawing-data">
                <div class="no-data-content">
                  <el-icon class="no-data-icon"><Grid /></el-icon>
                  <h3>暂无绘图数据</h3>
                  <p v-if="buildingList.length > 0">
                    检测到 {{ buildingList.length }} 栋楼，您可以开始创建新分区，拖拽楼栋到画布中进行分区管理
                  </p>
                  <p v-else>
                    暂无楼栋数据，请先添加楼栋信息，然后创建分区进行管理
                  </p>
                  <el-button type="primary" @click="createNewZone" :disabled="buildingList.length === 0">
                    <el-icon><Plus /></el-icon>
                    创建新分区
                  </el-button>
                  <el-button v-if="buildingList.length === 0" type="info" @click="goToBuildingManagement">
                    <el-icon><House /></el-icon>
                    去添加楼栋
                  </el-button>
                </div>
              </div>
              
              <!-- 绘图画布 -->
              <canvas
                v-else
                ref="canvasRef"
                class="drawing-canvas"
                :width="canvasWidth"
                :height="canvasHeight"
                @mousedown="handleCanvasMouseDown"
                @mousemove="handleCanvasMouseMove"
                @mouseup="handleCanvasMouseUp"
                @drop="handleDrop"
                @dragover="handleDragOver"
                @mouseleave="handleCanvasMouseLeave"
                @contextmenu.prevent
                @keydown="handleKeyDown"
                tabindex="0"
              ></canvas>
              
              <!-- 操作提示 -->
              <div class="canvas-tips" v-if="showTips && hasDrawingData">
                <div class="tips-content">
                  <h4>操作提示</h4>
                  <ul>
                    <li>从左侧拖拽楼栋到画布中</li>
                    <li>点击"选择"按钮可以选中和移动楼栋</li>
                    <li>选中楼栋后按Delete键或右键删除</li>
                    <li>点击右侧分区列表可以编辑分区</li>
                    <li>点击"保存"按钮保存当前设置</li>
                  </ul>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 右侧分区属性面板 -->
        <div class="zone-panel">
          <el-card class="panel-card" shadow="never">
            <template #header>
              <div class="card-header">
                <el-icon><Setting /></el-icon>
                <span>分区属性</span>
              </div>
            </template>

            <div class="panel-content">
              <!-- 分区列表 -->
              <div class="zone-list">
                <div
                  v-for="zone in allZones"
                  :key="zone.id"
                  class="zone-item"
                  :class="{ 
                    'zone-active': selectedZone?.id === zone.id,
                    'zone-not-in-drawing': !getZoneInDrawingStatus(zone.id)
                  }"
                  @click="selectZone(zone)"
                >
                  <div class="zone-color" :style="{ backgroundColor: zone.color }"></div>
                  <div class="zone-info">
                    <div class="zone-name">
                      {{ zone.zoneName || zone.name }}
                      <el-tag v-if="!getZoneInDrawingStatus(zone.id)" size="small" type="warning" class="zone-status-tag">
                        未放置
                      </el-tag>
                    </div>
                    <div class="zone-buildings">{{ getZoneBuildingCount(zone.id) }}栋楼</div>
                  </div>
                  <div class="zone-actions">
                    <el-button
                      type="danger"
                      size="small"
                      @click.stop="deleteZone(zone)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>

              <!-- 分区编辑表单 -->
              <div class="zone-edit-form" v-if="selectedZone">
                <el-form :model="selectedZone" label-width="80px" size="small">
                  <el-form-item label="分区名称">
                    <el-input v-model="selectedZone.name" placeholder="请输入分区名称" disabled />
                  </el-form-item>
                  
                  <el-form-item label="分区颜色">
                    <el-color-picker v-model="selectedZone.color" @change="updateZoneColor" />
                  </el-form-item>
                  
                  <el-form-item label="包含楼栋">
                    <div class="building-tags">
                      <el-tag
                        v-for="building in (selectedZone.buildings || [])"
                        :key="building.id"
                        closable
                        @close="removeBuildingFromZone(building)"
                      >
                        {{ building.buildingName }}
                      </el-tag>
                      <div v-if="(selectedZone.buildings || []).length === 0" class="no-buildings">
                        暂无楼栋
                      </div>
                    </div>
                  </el-form-item>
                  
                  <el-form-item label="分区面积">
                    <span>{{ selectedZone.area ? selectedZone.area.toFixed(2) : '0' }} 平方米</span>
                  </el-form-item>
                  
                  <!-- 编辑按钮 -->
                  <el-form-item>
                    <el-button type="primary" @click="openEditDialog">
                      <el-icon><EditPen /></el-icon>
                      编辑分区信息
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 创建新分区 -->
              <div class="create-zone">
                <el-button type="primary" @click="createNewZone">
                  <el-icon><Plus /></el-icon>
                  创建新分区
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
    
    <!-- 分区信息编辑对话框 -->
    <ZoneInfoEditDialog
      v-model="editDialogVisible"
      :zone-data="editZoneData"
      @success="handleEditSuccess"
    />
    
    <!-- 创建分区对话框 -->
    <ZoneInfoEditDialog
      v-model="createZoneDialogVisible"
      :community-id="selectedCommunity"
      :property-company-id="communityInfo?.propertyCompanyId"
      @success="handleCreateZoneSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Grid, House, User, Plus, Pointer, EditPen, Delete, 
  ZoomOut, ZoomIn, Check, Setting, RefreshLeft, RefreshRight, Location, MapLocation 
} from '@element-plus/icons-vue'
import { communityApi } from '@/api/community'
import { buildingApi } from '@/api/building'
import { zoneApi } from '@/api/zone'
import { regionApi } from '@/api/region'
import { zoneManagementApi } from '@/api/zoneManagement'
import ZoneInfoEditDialog from '@/components/zone/ZoneInfoEditDialog.vue'

// 类型定义
interface Community {
  id: number
  communityName: string
  communityCode: string
  propertyCompanyId?: number
  address: string
  totalBuildings: number
  totalHouseholds: number
  regionId?: number
  regionName?: string
  latitude?: number
  longitude?: number
  occupancyRate?: number
  buildingTypes?: string[]
  contactPhone?: string
  managerName?: string
  remark?: string
  status?: number
  createTime?: string
  updateTime?: string
}

interface Building {
  id: number
  buildingName: string
  buildingTypeName: string
  buildingType: string
  x?: number
  y?: number
  position?: { x: number; y: number }
}

interface Zone {
  id: number
  name: string
  zoneName?: string // 后端返回的分区名称字段
  color: string
  points: string
  textX: number
  textY: number
  buildings: Building[]
  area?: number // 新增面积属性
}

// 路由
const route = useRoute()

// 响应式数据
const selectedCommunity = ref<number>()
const selectedBuilding = ref<Building>()
const selectedZone = ref<Zone>()

// 社区进入状态相关数据
const communityEntryState = ref<{
  isFirstEntry: boolean
  hasExistingZones: boolean
  zoneCount: number
  lastModifiedTime?: string
  operationMode: 'CREATE' | 'UPDATE'
}>({
  isFirstEntry: true,
  hasExistingZones: false,
  zoneCount: 0,
  operationMode: 'CREATE'
})

// 社区信息
const communityInfo = ref<Community | null>(null)
const communityLoading = ref(false)

// 区域路径信息
const regionPathInfo = ref<{
  province?: string
  city?: string
  district?: string
  street?: string
  fullPath?: string
}>({})

// 楼栋列表
const apiBuildingList = ref<Building[]>([])
const buildingLoading = ref(false)


// Canvas相关
const canvasRef = ref<HTMLCanvasElement>()
const canvasWidth = ref(800)
const canvasHeight = ref(600)
const ctx = ref<CanvasRenderingContext2D>()

// 绘图相关
const currentTool = ref<'select'>('select')
const isSelectMode = ref(false)
const zoomLevel = ref(1)
const isDrawing = ref(false)
const drawingPoints = ref<{ x: number; y: number }[]>([])

// 分区拖拽相关
const isDraggingZone = ref(false)
const draggedZone = ref<Zone | null>(null)
const draggedVertexIndex = ref<number>(-1)
const dragStartPoint = ref<{ x: number; y: number } | null>(null)
const hoveredZone = ref<Zone | null>(null)
const hoveredVertexIndex = ref<number>(-1)

// 操作历史
const operationHistory = ref<Array<{ type: string; data: any; timestamp: number }>>([])
const currentHistoryIndex = ref(-1)
const canUndo = computed(() => currentHistoryIndex.value > 0)
const canRedo = computed(() => currentHistoryIndex.value < operationHistory.value.length - 1)

// 提示显示
const showTips = ref(true)

// 数据
const placedBuildings = ref<Building[]>([])
const zones = ref<Zone[]>([])
const zoneListData = ref<any[]>([]) // 存储从API获取的分区列表数据，避免重复调用
const buildingStatus = ref(new Map<number, 'available' | 'used'>()) // 跟踪楼栋使用状态

// 计算属性：所有分区列表（包括不在绘图区域中的分区）
const allZones = computed(() => {
  // 合并绘图区域中的分区和API获取的分区列表
  const drawingZones = zones.value
  const apiZones = zoneListData.value.map((zone: any) => ({
    id: zone.id,
    name: zone.zoneName || zone.name || `分区${zone.id}`,
    zoneName: zone.zoneName,
    color: zone.zoneColor || zone.color || '#409EFF',
    points: zone.zoneBoundary || zone.points || '',
    textX: zone.zoneCenterX || zone.textX || 0,
    textY: zone.zoneCenterY || zone.textY || 0,
    buildings: zone.buildings || [],
    area: zone.zoneArea || zone.area || 0
  }))
  
  // 去重：优先使用绘图区域中的数据，然后补充API数据中不在绘图区域的分区
  const zoneMap = new Map()
  
  // 先添加绘图区域中的分区
  drawingZones.forEach(zone => {
    zoneMap.set(zone.id, zone)
  })
  
  // 再添加API数据中不在绘图区域的分区
  apiZones.forEach(zone => {
    if (!zoneMap.has(zone.id)) {
      zoneMap.set(zone.id, zone)
    }
  })
  
  return Array.from(zoneMap.values())
})

// 编辑对话框相关
const editDialogVisible = ref(false)
const editZoneData = ref<any>(null)

// 创建分区对话框相关
const createZoneDialogVisible = ref(false)

// 加载状态
const loading = ref(false)

// 楼栋拖拽移动相关
const isDraggingPlacedBuilding = ref(false)
const draggedPlacedBuilding = ref<Building | null>(null)
const dragStartPosition = ref<{ x: number; y: number } | null>(null)

// 画布内楼栋移动函数定义
const handlePlacedBuildingDragStart = (event: DragEvent, building: Building) => {
  console.log('handlePlacedBuildingDragStart called', building) // 添加调试日志
  isDraggingPlacedBuilding.value = true
  draggedPlacedBuilding.value = building
  dragStartPosition.value = { x: building.x || 0, y: building.y || 0 }
  
  if (event.dataTransfer) {
    event.dataTransfer.setData('text/plain', JSON.stringify(building))
    event.dataTransfer.setData('dragType', 'moveInCanvas')
  }
}

const handlePlacedBuildingDragEnd = () => {
  isDraggingPlacedBuilding.value = false
  draggedPlacedBuilding.value = null
  dragStartPosition.value = null
}

// 使用API数据的楼栋列表
const buildingList = computed(() => apiBuildingList.value)

const filteredBuildings = computed(() => {
  // 只显示可用的楼栋（未使用的）
  return buildingList.value.filter(building => buildingStatus.value.get(building.id) !== 'used')
})

// 判断是否有绘图数据
const hasDrawingData = computed(() => {
  // 修改判断逻辑：只要有分区数据或楼栋数据就认为有绘图数据
  return zones.value.length > 0 || placedBuildings.value.length > 0
})

// 获取分区在绘图区域中的状态
const getZoneInDrawingStatus = (zoneId: number) => {
  return zones.value.some(z => z.id === zoneId)
}

// 方法

// 获取区域路径信息
const loadRegionPathInfo = async (regionId: number) => {
  try {
    const response = await regionApi.getRegionPath(regionId)
    if (response.code === 200 && response.data) {
      const regionPath = response.data
      
      // 解析区域路径，提取省市区街道信息
      const pathInfo: any = {}
      const fullPathParts: string[] = []
      
      regionPath.forEach((region: any) => {
        fullPathParts.push(region.regionName)
        
        // 根据区域类型分类
        switch (region.regionType) {
          case 1: // 省
            pathInfo.province = region.regionName
            break
          case 2: // 市
            pathInfo.city = region.regionName
            break
          case 3: // 区县
            pathInfo.district = region.regionName
            break
          case 4: // 街道
            pathInfo.street = region.regionName
            break
        }
      })
      
      pathInfo.fullPath = fullPathParts.join(' ')
      regionPathInfo.value = pathInfo
      
      console.log('区域路径信息加载成功:', pathInfo)
    } else {
      console.warn('加载区域路径信息失败')
    }
  } catch (error) {
    console.error('加载区域路径信息失败:', error)
  }
}

// 加载社区信息
const loadCommunityInfo = async (communityId: number) => {
  try {
    console.log('开始加载社区信息，社区ID:', communityId)
    const response = await communityApi.getCommunityDetail(communityId)
    
    if (response.code === 200 && response.data) {
      communityInfo.value = response.data
      console.log('社区信息加载完成:', communityInfo.value)
      
      // 如果有区域ID，加载区域路径信息
      if (response.data.regionId) {
        await loadRegionPathInfo(response.data.regionId)
      }
    } else {
      console.warn('加载社区信息失败，使用默认信息')
      communityInfo.value = {
        id: communityId,
        communityName: `社区${communityId}`,
        communityCode: `COMM${communityId}`,
        propertyCompanyId: 1,
        address: '未知地址',
        totalBuildings: 0,
        totalHouseholds: 0
      }
    }
  } catch (error) {
    console.error('加载社区信息失败:', error)
    // 使用默认社区信息，确保页面能正常显示
    communityInfo.value = {
      id: communityId,
      communityName: `社区${communityId}`,
      communityCode: `COMM${communityId}`,
      propertyCompanyId: 1,
      address: '未知地址',
      totalBuildings: 0,
      totalHouseholds: 0
    }
  }
}

// 加载楼栋列表
const loadBuildingList = async (communityId: number) => {
  try {
    console.log('开始加载楼栋列表，社区ID:', communityId)
    const response = await buildingApi.getBuildingsByCommunity(communityId)
    
    if (response.code === 200 && response.data) {
      // 转换API数据格式为组件需要的格式
      apiBuildingList.value = response.data.map((building: any) => ({
        id: building.id,
        buildingName: building.buildingName,
        buildingTypeName: building.buildingTypeName || building.buildingType || '住宅楼',
        buildingType: building.buildingType || 'residential'
      }))
      console.log('楼栋列表加载完成，楼栋数量:', apiBuildingList.value.length)
      
      // 初始化所有楼栋状态为可用
      apiBuildingList.value.forEach(building => {
        buildingStatus.value.set(building.id, 'available')
      })
      console.log('楼栋状态初始化完成，所有楼栋设置为可用状态')
    } else {
      console.warn('加载楼栋列表失败，使用空列表')
      apiBuildingList.value = []
    }
  } catch (error) {
    console.error('加载楼栋列表失败:', error)
    // 使用空楼栋列表，确保页面能正常显示
    apiBuildingList.value = []
  }
}

const selectBuilding = (building: Building) => {
  selectedBuilding.value = building
}

const setTool = (tool: 'select') => {
  currentTool.value = tool
}

const toggleSelectMode = () => {
  isSelectMode.value = !isSelectMode.value
  if (!isSelectMode.value) {
    // 取消选择状态，清除选中分区和楼栋
    selectedZone.value = undefined
    selectedBuilding.value = undefined
    redrawCanvas()
  }
}

const zoomIn = () => {
  if (zoomLevel.value < 2) {
    zoomLevel.value += 0.1
    redrawCanvas()
  }
}

const zoomOut = () => {
  if (zoomLevel.value > 0.3) {
    zoomLevel.value -= 0.1
    redrawCanvas()
  }
}



// Canvas绘制函数
const redrawCanvas = () => {
  console.log('开始重新绘制画布')
  console.log('ctx.value:', ctx.value)
  console.log('canvasWidth.value:', canvasWidth.value)
  console.log('canvasHeight.value:', canvasHeight.value)
  
  // 如果Canvas上下文未初始化，尝试初始化
  if (!ctx.value) {
    console.log('Canvas上下文未初始化，尝试初始化...')
    if (canvasRef.value) {
      ctx.value = canvasRef.value.getContext('2d')
      console.log('Canvas上下文初始化结果:', ctx.value)
    }
    
    if (!ctx.value) {
      console.error('Canvas上下文初始化失败，跳过绘制')
      return
    }
  }
  
  // 清空画布并设置白色背景
  ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value)
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
  console.log('画布已清空并设置白色背景')
  
  // 绘制网格背景
  drawGrid()
  console.log('网格背景绘制完成')
  
  // 绘制分区
  drawZones()
  console.log('分区绘制完成')
  
  // 绘制楼栋
  drawBuildings()
  console.log('楼栋绘制完成')
  
  // 绘制拖拽手柄
  if (selectedZone.value) {
    drawZoneHandles(selectedZone.value)
    console.log('拖拽手柄绘制完成')
  }
  
  console.log('画布重新绘制完成')
}

// 绘制网格
const drawGrid = () => {
  if (!ctx.value) return
  
  const gridSize = 20 * zoomLevel.value
  ctx.value.strokeStyle = '#e0e0e0'
  ctx.value.lineWidth = 1
  
  for (let x = 0; x <= canvasWidth.value; x += gridSize) {
    ctx.value.beginPath()
    ctx.value.moveTo(x, 0)
    ctx.value.lineTo(x, canvasHeight.value)
    ctx.value.stroke()
  }
  
  for (let y = 0; y <= canvasHeight.value; y += gridSize) {
    ctx.value.beginPath()
    ctx.value.moveTo(0, y)
    ctx.value.lineTo(canvasWidth.value, y)
    ctx.value.stroke()
  }
}

// 绘制分区
const drawZones = () => {
  if (!ctx.value) return
  
  console.log('开始绘制分区，分区数量:', zones.value.length)
  console.log('分区数据:', zones.value)
  
  zones.value.forEach((zone, index) => {
    console.log(`绘制分区 ${index + 1}:`, zone)
    console.log(`分区 ${index + 1} 的points数据:`, zone.points)
    
    const points = parseZonePoints(zone.points)
    console.log(`分区 ${index + 1} 解析后的points:`, points)
    
    if (points.length < 3) {
      console.warn(`分区 ${index + 1} 点数不足，跳过绘制`)
      return
    }
    
    ctx.value!.beginPath()
    ctx.value!.moveTo(points[0].x * zoomLevel.value, points[0].y * zoomLevel.value)
    
    for (let i = 1; i < points.length; i++) {
      ctx.value!.lineTo(points[i].x * zoomLevel.value, points[i].y * zoomLevel.value)
    }
    
    ctx.value!.closePath()
    ctx.value!.fillStyle = zone.color + '20'
    ctx.value!.fill()
    ctx.value!.strokeStyle = zone.color
    ctx.value!.lineWidth = 2
    ctx.value!.stroke()
    
    console.log(`分区 ${index + 1} 绘制完成`)
  })
}

// 绘制楼栋
const drawBuildings = () => {
  if (!ctx.value) return
  
  console.log('开始绘制楼栋，楼栋数量:', placedBuildings.value.length)
  console.log('楼栋数据:', placedBuildings.value)
  
  placedBuildings.value.forEach((building, index) => {
    console.log(`绘制楼栋 ${index + 1}:`, building)
    
    if (building.x === undefined || building.y === undefined) {
      console.warn(`楼栋 ${index + 1} 位置信息缺失，跳过绘制`)
      return
    }
    
    const x = building.x * zoomLevel.value
    const y = building.y * zoomLevel.value
    const width = 40 * zoomLevel.value  // 进一步加宽
    const height = 28 * zoomLevel.value // 增加高度
    
    console.log(`楼栋 ${index + 1} 绘制位置: x=${x}, y=${y}, width=${width}, height=${height}`)
    
    // 判断是否为选中的楼栋
    const isSelected = selectedBuilding.value?.id === building.id
    
    // 绘制楼栋图标（长方形）
    ctx.value!.fillStyle = isSelected ? '#ff6b6b' : '#409eff'
    ctx.value!.fillRect(x - width/2, y - height/2, width, height)
    
    // 绘制边框线条（更醒目）
    ctx.value!.strokeStyle = isSelected ? '#e74c3c' : '#2c5aa0'
    ctx.value!.lineWidth = isSelected ? 3 * zoomLevel.value : 2 * zoomLevel.value
    ctx.value!.strokeRect(x - width/2, y - height/2, width, height)
    
    // 如果是选中的楼栋，绘制选中标识
    if (isSelected) {
      ctx.value!.strokeStyle = '#e74c3c'
      ctx.value!.lineWidth = 2 * zoomLevel.value
      ctx.value!.setLineDash([5 * zoomLevel.value, 5 * zoomLevel.value])
      ctx.value!.strokeRect(x - width/2 - 5, y - height/2 - 5, width + 10, height + 10)
      ctx.value!.setLineDash([]) // 重置虚线样式
    }
    
    // 绘制楼栋名称
    ctx.value!.fillStyle = '#fff'
    ctx.value!.font = `${12 * zoomLevel.value}px Arial`
    ctx.value!.textAlign = 'center'
    ctx.value!.fillText(building.buildingName, x, y + 4 * zoomLevel.value)
    
    console.log(`楼栋 ${index + 1} 绘制完成`)
  })
}

// 绘制分区拖拽手柄
const drawZoneHandles = (zone: Zone) => {
  if (!ctx.value) return
  
  const points = parseZonePoints(zone.points)
  const handleSize = 6 * zoomLevel.value
  
  points.forEach((point, index) => {
    const x = point.x * zoomLevel.value
    const y = point.y * zoomLevel.value
    
    ctx.value!.fillStyle = '#fff'
    ctx.value!.strokeStyle = zone.color
    ctx.value!.lineWidth = 2
    ctx.value!.beginPath()
    ctx.value!.arc(x, y, handleSize, 0, 2 * Math.PI)
    ctx.value!.fill()
    ctx.value!.stroke()
  })
}

// 解析分区点坐标
const parseZonePoints = (pointsStr: string): Array<{ x: number; y: number }> => {
  try {
    // 尝试解析JSON格式
    if (pointsStr.startsWith('[') || pointsStr.startsWith('{')) {
      return JSON.parse(pointsStr)
    }
    
    // 兼容旧格式：空格分割的坐标
    return pointsStr.split(' ').map(point => {
      const [x, y] = point.split(',').map(Number)
      return { x, y }
    })
  } catch (error) {
    console.error('解析分区点坐标失败:', error, '原始数据:', pointsStr)
    return []
  }
}

// 从左侧库拖拽到画布（复制）
const handleDragStart = (event: DragEvent, building: Building) => {
  if (event.dataTransfer) {
    event.dataTransfer.setData('text/plain', JSON.stringify(building))
    event.dataTransfer.setData('dragType', 'fromLibrary')
  }
}

// 处理画布内楼栋拖拽移动
const handleCanvasMouseMove = (event: MouseEvent) => {
  if (!canvasRef.value) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const x = (event.clientX - rect.left) / zoomLevel.value
  const y = (event.clientY - rect.top) / zoomLevel.value
  
  // 处理分区拖拽
  if (isDraggingZone.value && draggedZone.value && draggedVertexIndex.value >= 0) {
    // 网格对齐
    const gridSize = 20
    const alignedX = Math.round(x / gridSize) * gridSize
    const alignedY = Math.round(y / gridSize) * gridSize
    
    // 更新顶点位置
    const points = parseZonePoints(draggedZone.value.points)
    points[draggedVertexIndex.value] = { x: alignedX, y: alignedY }
    draggedZone.value.points = points.map(p => `${p.x},${p.y}`).join(' ')
    
    // 重新绘制
    redrawCanvas()
    return
  }
  
  // 处理楼栋拖拽移动
  if (isDraggingPlacedBuilding.value && draggedPlacedBuilding.value) {
    // 网格对齐
    const gridSize = 20
    const alignedX = Math.round(x / gridSize) * gridSize
    const alignedY = Math.round(y / gridSize) * gridSize
    
    // 直接更新位置，不创建新对象
    draggedPlacedBuilding.value.x = alignedX
    draggedPlacedBuilding.value.y = alignedY
    
    // 重新绘制
    redrawCanvas()
  }
}

// 添加操作历史
const addToHistory = (type: string, data: any) => {
  // 移除当前位置之后的历史记录
  operationHistory.value.splice(currentHistoryIndex.value + 1)
  
  // 添加新操作
  operationHistory.value.push({
    type,
    data,
    timestamp: Date.now()
  })
  
  currentHistoryIndex.value = operationHistory.value.length - 1
}

// 撤销操作
const undoLastOperation = () => {
  if (currentHistoryIndex.value > 0) {
    currentHistoryIndex.value--
    const operation = operationHistory.value[currentHistoryIndex.value]
    restoreFromHistory(operation)
  }
}

// 重做操作
const redoLastOperation = () => {
  if (currentHistoryIndex.value < operationHistory.value.length - 1) {
    currentHistoryIndex.value++
    const operation = operationHistory.value[currentHistoryIndex.value]
    restoreFromHistory(operation)
  }
}

// 从历史记录恢复
const restoreFromHistory = (operation: { type: string; data: any }) => {
  switch (operation.type) {
    case 'zone_created':
      zones.value = operation.data.zones
      break
    case 'zone_updated':
      zones.value = operation.data.zones
      break
    case 'zone_deleted':
      zones.value = operation.data.zones
      break
    case 'building_placed':
      placedBuildings.value = operation.data.buildings
      buildingStatus.value = operation.data.buildingStatus
      break
  }
  redrawCanvas()
}

// 更新分区颜色
const updateZoneColor = () => {
  if (selectedZone.value) {
    redrawCanvas()
    addToHistory('zone_updated', { zones: [...zones.value] })
  }
}

// 处理画布鼠标离开
const handleCanvasMouseLeave = () => {
  isDraggingZone.value = false
  isDraggingPlacedBuilding.value = false
  draggedZone.value = null
  draggedPlacedBuilding.value = null
  draggedVertexIndex.value = -1
}

// 处理键盘事件
const handleKeyDown = (event: KeyboardEvent) => {
  // 删除键删除选中的楼栋
  if (event.key === 'Delete' || event.key === 'Backspace') {
    if (selectedBuilding.value) {
      event.preventDefault()
      deleteSelectedBuilding()
    }
  }
  
  // ESC键取消选择
  if (event.key === 'Escape') {
    selectedBuilding.value = undefined
    redrawCanvas()
  }
}

// 删除选中的楼栋
const deleteSelectedBuilding = () => {
  if (!selectedBuilding.value) return
  
  ElMessageBox.confirm(
    `确定要删除楼栋"${selectedBuilding.value.buildingName}"吗？`,
    '确认删除楼栋',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'delete-building-dialog'
    }
  ).then(() => {
    removeBuilding(selectedBuilding.value!)
    selectedBuilding.value = undefined
    ElMessage.success('楼栋删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  if (!event.dataTransfer) return

  const buildingData = event.dataTransfer.getData('text/plain')
  const dragType = event.dataTransfer.getData('dragType')
  
  if (buildingData) {
    const building: Building = JSON.parse(buildingData)
    
    if (dragType === 'fromLibrary') {
      // 从左侧库拖拽到画布（复制）
      const rect = canvasRef.value?.getBoundingClientRect()
      if (rect) {
        const x = (event.clientX - rect.left) / zoomLevel.value
        const y = (event.clientY - rect.top) / zoomLevel.value
        
        // 网格对齐
        const gridSize = 20
        const alignedX = Math.round(x / gridSize) * gridSize
        const alignedY = Math.round(y / gridSize) * gridSize
        
        const placedBuilding: Building = {
          ...building,
          x: alignedX,
          y: alignedY
        }
        
        placedBuildings.value.push(placedBuilding)
        
        // 更新楼栋状态为已使用，从左侧库中消失
        buildingStatus.value.set(building.id, 'used')
        
        // 自动识别楼栋所属分区
        updateBuildingZoneAssignment(placedBuilding)
        
        // 添加到历史记录
        addToHistory('building_placed', {
          buildings: [...placedBuildings.value],
          buildingStatus: new Map(buildingStatus.value)
        })
        
        redrawCanvas()
        
        ElMessage.success(`楼栋"${building.buildingName}"已添加到画布中`)
      }
    } else if (dragType === 'moveInCanvas') {
      // 画布内楼栋移动，拖拽结束时更新分区归属
      if (draggedPlacedBuilding.value) {
        updateBuildingZoneAssignment(draggedPlacedBuilding.value)
        redrawCanvas()
      }
    }
  }
}

// 生成默认分区框
const generateDefaultZone = (x: number, y: number): Zone => {
  const defaultWidth = 200
  const defaultHeight = 150
  
  // 网格对齐
  const gridSize = 20
  const alignedX = Math.round(x / gridSize) * gridSize
  const alignedY = Math.round(y / gridSize) * gridSize
  
  const points = [
    `${alignedX},${alignedY}`,
    `${alignedX + defaultWidth},${alignedY}`,
    `${alignedX + defaultWidth},${alignedY + defaultHeight}`,
    `${alignedX},${alignedY + defaultHeight}`
  ].join(' ')
  
  return {
    id: Date.now(),
    name: `分区${zones.value.length + 1}`,
    color: getRandomColor(),
    points,
    textX: alignedX + defaultWidth / 2,
    textY: alignedY + defaultHeight / 2,
    buildings: [],
    area: defaultWidth * defaultHeight
  }
}

// 生成带后端ID的默认分区框
const generateDefaultZoneWithBackendId = (x: number, y: number, zoneId: number, zoneData: any): Zone => {
  const defaultWidth = 200
  const defaultHeight = 150
  
  // 网格对齐
  const gridSize = 20
  const alignedX = Math.round(x / gridSize) * gridSize
  const alignedY = Math.round(y / gridSize) * gridSize
  
  const points = [
    `${alignedX},${alignedY}`,
    `${alignedX + defaultWidth},${alignedY}`,
    `${alignedX + defaultWidth},${alignedY + defaultHeight}`,
    `${alignedX},${alignedY + defaultHeight}`
  ].join(' ')
  
  return {
    id: zoneId, // 使用后端生成的分区ID
    name: zoneData.zoneName,
    color: zoneData.zoneColor,
    points,
    textX: alignedX + defaultWidth / 2,
    textY: alignedY + defaultHeight / 2,
    buildings: [],
    area: defaultWidth * defaultHeight
  }
}

// 检查点是否在拖拽手柄范围内
const isPointInHandle = (point: { x: number; y: number }, handlePoint: { x: number; y: number }): boolean => {
  const handleSize = 8 * zoomLevel.value
  const distance = Math.sqrt(
    Math.pow(point.x - handlePoint.x * zoomLevel.value, 2) + 
    Math.pow(point.y - handlePoint.y * zoomLevel.value, 2)
  )
  return distance <= handleSize
}

// 计算多边形面积
const calculatePolygonArea = (points: Array<{ x: number; y: number }>): number => {
  let area = 0
  for (let i = 0; i < points.length; i++) {
    const j = (i + 1) % points.length
    area += points[i].x * points[j].y
    area -= points[j].x * points[i].y
  }
  return Math.abs(area) / 2
}

// 更新分区面积
const updateZoneArea = (zone: Zone) => {
  try {
    const points = parseZonePoints(zone.points)
    if (points.length >= 3) {
      const area = calculatePolygonArea(points)
      zone.area = area
      console.log(`分区 ${zone.name} 面积更新为: ${area.toFixed(2)} 平方米`)
    } else {
      zone.area = 0
    }
  } catch (error) {
    console.error('计算分区面积失败:', error)
    zone.area = 0
  }
}

// 更新所有分区面积
const updateAllZoneAreas = () => {
  zones.value.forEach(zone => {
    updateZoneArea(zone)
  })
}

// 更新所有楼栋的分区归属
const updateAllBuildingZoneAssignments = () => {
  placedBuildings.value.forEach(building => {
    updateBuildingZoneAssignment(building)
  })
}

// 检查点是否在楼栋范围内
const isPointInBuilding = (point: { x: number; y: number }, building: Building): boolean => {
  if (building.x === undefined || building.y === undefined) return false
  
  const buildingX = building.x * zoomLevel.value
  const buildingY = building.y * zoomLevel.value
  const width = 30 * zoomLevel.value
  const height = 20 * zoomLevel.value
  
  return point.x >= buildingX - width/2 && 
         point.x <= buildingX + width/2 && 
         point.y >= buildingY - height/2 && 
         point.y <= buildingY + height/2
}

const handleCanvasMouseDown = (event: MouseEvent) => {
  if (!canvasRef.value) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const x = (event.clientX - rect.left) / zoomLevel.value
  const y = (event.clientY - rect.top) / zoomLevel.value
  
  if (isSelectMode.value) {
    // 首先检查是否点击了楼栋
    for (const building of placedBuildings.value) {
      if (isPointInBuilding({ x: event.clientX - rect.left, y: event.clientY - rect.top }, building)) {
        selectedBuilding.value = building
        
        // 右键删除楼栋
        if (event.button === 2) { // 右键
          event.preventDefault()
          selectedBuilding.value = building
          deleteSelectedBuilding()
          return
        }
        
        // 左键选中楼栋并开始拖拽
        if (event.button === 0) { // 左键
          selectedBuilding.value = building
          isDraggingPlacedBuilding.value = true
          draggedPlacedBuilding.value = building
          dragStartPosition.value = { x: building.x || 0, y: building.y || 0 }
          redrawCanvas()
        }
        return
      }
    }
    
    // 检查是否点击了分区拖拽手柄
    for (const zone of zones.value) {
      const points = parseZonePoints(zone.points)
      for (let i = 0; i < points.length; i++) {
        if (isPointInHandle({ x: event.clientX - rect.left, y: event.clientY - rect.top }, points[i])) {
          isDraggingZone.value = true
          draggedZone.value = zone
          draggedVertexIndex.value = i
          dragStartPoint.value = { x, y }
          selectedZone.value = zone
          return
        }
      }
    }
  }
}

const handleCanvasMouseUp = () => {
  if (isDraggingZone.value) {
    isDraggingZone.value = false
    draggedZone.value = null
    draggedVertexIndex.value = -1
    dragStartPoint.value = null
    
    // 更新分区面积
    if (selectedZone.value) {
      updateZoneArea(selectedZone.value)
    }
    
    // 更新楼栋归属
    updateAllBuildingZoneAssignments()
    
    // 添加到历史记录
    addToHistory('zone_updated', { zones: [...zones.value] })
  }
  
  if (isDraggingPlacedBuilding.value && draggedPlacedBuilding.value) {
    // 更新楼栋归属
    updateBuildingZoneAssignment(draggedPlacedBuilding.value)
    
    // 添加到历史记录
    addToHistory('building_moved', {
      buildings: [...placedBuildings.value],
      buildingStatus: new Map(buildingStatus.value)
    })
  }
  
  isDraggingPlacedBuilding.value = false
  draggedPlacedBuilding.value = null
}

const getRandomColor = () => {
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  return colors[Math.floor(Math.random() * colors.length)]
}

const selectZone = async (zone: Zone) => {
  console.log('选中分区:', zone)
  
  // 检查分区是否在绘图区域中
  const zoneInDrawing = zones.value.find(z => z.id === zone.id)
  
  if (!zoneInDrawing) {
    console.log('选中的分区不在绘图区域中，自动放置到绘图区域')
    
    // 为分区生成默认绘图数据并放置到绘图区域
    const newZone = await generateZoneDrawingData(zone)
    
    // 添加到绘图区域
    zones.value.push(newZone)
    console.log('分区已添加到绘图区域:', newZone)
    
    // 重新绘制画布
    redrawCanvas()
    
    // 显示成功提示
    ElMessage.success(`分区"${zone.name}"已自动放置到绘图区域`)
  }
  
  // 设置选中的分区（优先使用绘图区域中的分区数据，如果没有则使用allZones中的数据）
  selectedZone.value = zoneInDrawing || zone
  // 自动切换到选择模式
  isSelectMode.value = true
  // 重新绘制Canvas以显示拖拽手柄
  redrawCanvas()
}

const openEditDialog = () => {
  if (selectedZone.value) {
    editZoneData.value = selectedZone.value
    editDialogVisible.value = true
  }
}

const handleEditSuccess = () => {
  // 编辑成功后刷新分区数据
  if (selectedZone.value) {
    loadZoneDetail(selectedZone.value.id)
  }
}

const loadZoneDetail = async (zoneId: number) => {
  try {
    const response = await zoneApi.getZoneDetail(zoneId)
    if (response.code === 200 && response.data) {
      // 更新选中的分区数据
      if (selectedZone.value && selectedZone.value.id === zoneId) {
        Object.assign(selectedZone.value, response.data)
      }
      // 更新分区列表中的数据
      const zoneIndex = zones.value.findIndex(z => z.id === zoneId)
      if (zoneIndex !== -1) {
        Object.assign(zones.value[zoneIndex], response.data)
      }
      redrawCanvas()
    }
  } catch (error) {
    console.error('加载分区详情失败:', error)
    ElMessage.error('加载分区详情失败')
  }
}

const editZone = (zone: Zone) => {
  selectedZone.value = zone
}

const deleteZone = (zone: Zone) => {
  ElMessageBox.confirm(
    `确定要删除分区"${zone.name}"吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 从绘图区域中删除
    const drawingIndex = zones.value.findIndex(z => z.id === zone.id)
    if (drawingIndex > -1) {
      zones.value.splice(drawingIndex, 1)
    }
    
    // 从API数据中删除（如果存在）
    const apiIndex = zoneListData.value.findIndex((z: any) => z.id === zone.id)
    if (apiIndex > -1) {
      zoneListData.value.splice(apiIndex, 1)
    }
    
    if (selectedZone.value?.id === zone.id) {
      selectedZone.value = undefined
    }
    
    // 立即重新绘制Canvas
    redrawCanvas()
    
    ElMessage.success('分区删除成功')
  })
}

// 处理创建分区成功
const handleCreateZoneSuccess = async (zoneData: any) => {
  try {
    loading.value = true
    
    // 1. 调用后端API创建分区
    const createResponse = await zoneManagementApi.createZone({
      ...zoneData,
      communityId: selectedCommunity.value,
      propertyCompanyId: communityInfo.value?.propertyCompanyId
    })
    
    if (createResponse.code !== 200) {
      throw new Error(createResponse.message || '创建分区失败')
    }
    
    // 2. 获取后端生成的分区ID
    const zoneId = createResponse.data?.id
    if (!zoneId) {
      throw new Error('未获取到分区ID')
    }
    
    // 3. 生成默认分区框，位置在画布中心
    const centerX = canvasWidth.value / 2 / zoomLevel.value
    const centerY = canvasHeight.value / 2 / zoomLevel.value
    const newZone = generateDefaultZoneWithBackendId(centerX, centerY, zoneId, zoneData)
    
    // 4. 添加到分区列表
    zones.value.push(newZone)
    selectedZone.value = newZone
    
    // 5. 自动切换到选择模式
    isSelectMode.value = true
    
    // 6. 重新绘制Canvas
    redrawCanvas()
    
    // 7. 添加到历史记录
    addToHistory('zone_created', { zones: [...zones.value] })
    
    // 8. 自动保存绘图数据
    await saveZones()
    
    ElMessage.success('分区创建成功')
  } catch (error) {
    console.error('创建分区失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '创建分区失败')
  } finally {
    loading.value = false
  }
}

const createNewZone = () => {
  // 弹出创建分区对话框，强制用户输入分区信息
  createZoneDialogVisible.value = true
}

// 点与多边形位置关系算法
const isPointInPolygon = (point: { x: number; y: number }, polygon: Array<{ x: number; y: number }>) => {
  let inside = false
  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    if (((polygon[i].y > point.y) !== (polygon[j].y > point.y)) &&
        (point.x < (polygon[j].x - polygon[i].x) * (point.y - polygon[i].y) / 
         (polygon[j].y - polygon[i].y) + polygon[i].x)) {
      inside = !inside
    }
  }
  return inside
}



// 自动更新楼栋归属
const updateBuildingZoneAssignment = (building: Building) => {
  // 从所有分区中移除该楼栋
  zones.value.forEach(zone => {
    const index = zone.buildings.findIndex(b => b.id === building.id)
    if (index > -1) {
      zone.buildings.splice(index, 1)
    }
  })
  
  // 找到包含该楼栋的分区
  const containingZone = zones.value.find(zone => {
    const vertices = zone.points.split(' ').map(point => {
      const [x, y] = point.split(',').map(Number)
      return { x, y }
    })
    const buildingPosition = { x: building.x || 0, y: building.y || 0 }
    return isPointInPolygon(buildingPosition, vertices)
  })
  
  // 将楼栋添加到对应分区
  if (containingZone) {
    containingZone.buildings.push(building)
  }
}

// 删除楼栋
const removeBuilding = (building: Building) => {
  const index = placedBuildings.value.findIndex(b => b.id === building.id)
  if (index > -1) {
    placedBuildings.value.splice(index, 1)
    
    // 从所有分区中移除
    zones.value.forEach(zone => {
      const zoneIndex = zone.buildings.findIndex(b => b.id === building.id)
      if (zoneIndex > -1) {
        zone.buildings.splice(zoneIndex, 1)
      }
    })
    
    // 更新楼栋状态为可用，重新出现在左侧库中
    buildingStatus.value.set(building.id, 'available')
    
    // 立即重新绘制Canvas
    redrawCanvas()
    
    // 添加到历史记录
    addToHistory('building_removed', {
      buildings: [...placedBuildings.value],
      buildingStatus: new Map(buildingStatus.value)
    })
    
    ElMessage.success(`楼栋"${building.buildingName}"已删除，已重新添加到楼栋库中`)
  }
}

const removeBuildingFromZone = (building: Building) => {
  if (selectedZone.value) {
    const index = selectedZone.value.buildings.findIndex(b => b.id === building.id)
    if (index > -1) {
      selectedZone.value.buildings.splice(index, 1)
    }
  }
}

// 社区进入状态判断逻辑
const determineCommunityEntryState = async (communityId: number) => {
  console.log('=== 社区进入状态判断逻辑开始 ===')
  console.log('判断时间:', new Date().toLocaleString())
  console.log('社区ID:', communityId)
  
  try {
    // 调用API获取社区分区列表
    const response = await zoneApi.getZonesByCommunity(communityId)
    
    if (response.code === 200) {
      const zoneList = response.data || []
      const hasExistingZones = zoneList.length > 0
      const isFirstEntry = !hasExistingZones
      
      // 获取最后修改时间
      let lastModifiedTime: string | undefined
      if (hasExistingZones && zoneList.length > 0) {
        const latestZone = zoneList.reduce((latest: any, current: any) => {
          return new Date(current.updateTime) > new Date(latest.updateTime) ? current : latest
        })
        lastModifiedTime = latestZone.updateTime
      }
      
      // 判断操作模式
      const operationMode = isFirstEntry ? 'CREATE' : 'UPDATE'
      
      // 打印判断结果
      console.log('=== 社区进入状态判断结果 ===')
      console.log('是否初次进入:', isFirstEntry)
      console.log('是否有现有分区:', hasExistingZones)
      console.log('分区数量:', zoneList.length)
      console.log('最后修改时间:', lastModifiedTime)
      console.log('操作模式:', operationMode)
      
      // 打印分区详情（如果有）
      if (hasExistingZones) {
        console.log('=== 现有分区详情 ===')
        console.log('分区列表:', JSON.stringify(zoneList, null, 2))
      }
      
      // 打印判断逻辑说明
      console.log('=== 判断逻辑说明 ===')
      console.log('判断依据: 基于 sc_zone 分区表查询该社区是否有分区数据')
      console.log('判断条件: zoneList.length > 0')
      console.log('初次进入: 没有分区数据，操作模式为 CREATE')
      console.log('非初次进入: 有分区数据，操作模式为 UPDATE')
      
      // 打印用户提示信息
      console.log('=== 用户提示信息 ===')
      if (isFirstEntry) {
        console.log('用户提示: 欢迎使用分区管理功能！这是您第一次进入该社区的分区管理页面。')
        console.log('操作建议: 可以创建新分区、拖拽楼栋、设置分区边界等。')
      } else {
        console.log(`用户提示: 检测到该社区已有 ${zoneList.length} 个分区，正在加载现有数据...`)
        console.log('操作建议: 可以编辑现有分区、调整楼栋位置、修改分区边界等。')
        if (lastModifiedTime) {
          console.log(`最后修改时间: ${lastModifiedTime}`)
        }
      }
      
      // 打印完整的判断数据结构
      const entryStateData = {
        timestamp: new Date().toISOString(),
        communityId,
        isFirstEntry,
        hasExistingZones,
        zoneCount: zoneList.length,
        lastModifiedTime,
        operationMode,
        zoneList: hasExistingZones ? zoneList : [],
        judgmentLogic: {
          basedOn: 'sc_zone 分区表查询',
          condition: 'zoneList.length > 0',
          result: isFirstEntry ? 'CREATE 模式' : 'UPDATE 模式'
        }
      }
      
      console.log('=== 完整判断数据结构 ===')
      console.log(JSON.stringify(entryStateData, null, 2))
      
      // 更新状态
      communityEntryState.value = {
        isFirstEntry,
        hasExistingZones,
        zoneCount: zoneList.length,
        lastModifiedTime,
        operationMode
      }
      
      // 保存分区列表数据，避免重复调用
      zoneListData.value = zoneList
      
      // 返回判断结果
      return {
        isFirstEntry,
        hasExistingZones,
        zoneCount: zoneList.length,
        lastModifiedTime,
        operationMode,
        zoneList
      }
      
    } else {
      console.error('获取分区列表失败:', response.message)
      // 默认按初次进入处理
      console.log('=== 异常情况处理 ===')
      console.log('API调用失败，默认按初次进入处理')
      console.log('操作模式: CREATE')
      
      // 更新状态
      communityEntryState.value = {
        isFirstEntry: true,
        hasExistingZones: false,
        zoneCount: 0,
        operationMode: 'CREATE'
      }
      
      return {
        isFirstEntry: true,
        hasExistingZones: false,
        zoneCount: 0,
        operationMode: 'CREATE',
        zoneList: []
      }
    }
    
  } catch (error) {
    console.error('判断社区进入状态失败:', error)
    // 默认按初次进入处理
    console.log('=== 异常情况处理 ===')
    console.log('判断逻辑执行失败，默认按初次进入处理')
    console.log('操作模式: CREATE')
    
    // 更新状态
    communityEntryState.value = {
      isFirstEntry: true,
      hasExistingZones: false,
      zoneCount: 0,
      operationMode: 'CREATE'
    }
    
    return {
      isFirstEntry: true,
      hasExistingZones: false,
      zoneCount: 0,
      operationMode: 'CREATE',
      zoneList: []
    }
  }
}

const saveZones = async () => {
  try {
    loading.value = true
    
    // 构建绘图数据
    const drawingData = {
      timestamp: new Date().toISOString(),
      communityId: selectedCommunity.value,
      communityInfo: communityInfo.value,
      zones: zones.value,
      placedBuildings: placedBuildings.value,
      availableBuildings: filteredBuildings.value,
      canvasState: {
        width: canvasWidth.value,
        height: canvasHeight.value,
        zoomLevel: zoomLevel.value,
        isSelectMode: isSelectMode.value,
        currentTool: currentTool.value
      },
      operationHistory: {
        total: operationHistory.value.length,
        currentIndex: currentHistoryIndex.value,
        canUndo: canUndo.value,
        canRedo: canRedo.value
      },
      buildingStatus: Object.fromEntries(buildingStatus.value)
    }
    
    // 检查数据库中是否已存在绘图数据
    let existingDrawingData = null
    try {
      const response = await zoneManagementApi.getCommunityDrawingData(selectedCommunity.value!)
      if (response.code === 200 && response.data) {
        existingDrawingData = response.data
        console.log('获取到现有绘图数据:', existingDrawingData)
      }
    } catch (error) {
      // 如果获取失败，说明没有现有数据，这是正常的
      console.log('未找到现有绘图数据，将创建新数据')
    }
    
    let saveResponse
    if (existingDrawingData && existingDrawingData.id) {
      // 更新现有绘图数据
      console.log('更新现有绘图数据，ID:', existingDrawingData.id)
      saveResponse = await zoneManagementApi.updateDrawingData(existingDrawingData.id, drawingData)
    } else {
      // 创建新的绘图数据
      console.log('创建新的绘图数据')
      saveResponse = await zoneManagementApi.saveDrawingData({
        ...drawingData,
        propertyCompanyId: communityInfo.value?.propertyCompanyId
      })
    }
    
    if (saveResponse.code === 200) {
      ElMessage.success('分区数据保存成功')
      
      // 更新社区进入状态为非初次进入
      communityEntryState.value.isFirstEntry = false
      communityEntryState.value.operationMode = 'UPDATE'
    } else {
      throw new Error(saveResponse.message || '保存失败')
    }
  } catch (error) {
    console.error('保存分区数据失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '保存失败')
  } finally {
    loading.value = false
  }
}

const resetCanvas = () => {
  placedBuildings.value = []
  zones.value = []
  selectedBuilding.value = undefined
  selectedZone.value = undefined
  zoomLevel.value = 1
}

// 加载绘图数据
const loadDrawingData = async (communityId: number) => {
  try {
    console.log('开始加载绘图数据，社区ID:', communityId)
    
    // 调用后端接口获取绘图数据
    const response = await zoneManagementApi.getCommunityDrawingData(communityId)
    
    if (response.code === 200 && response.data) {
      console.log('绘图数据加载成功:', response.data)
      
      const drawingData = response.data
      
      // 解析绘图数据
      if (drawingData.zones && Array.isArray(drawingData.zones)) {
        zones.value = drawingData.zones.map((zone: any) => {
          const zoneData = {
            id: zone.id,
            name: zone.zoneName || zone.name || `分区${zone.id}`,
            zoneName: zone.zoneName,
            color: zone.zoneColor || zone.color || getRandomColor(),
            points: zone.zoneBoundary || zone.points || '',
            textX: zone.zoneCenterX || zone.textX || 0,
            textY: zone.zoneCenterY || zone.textY || 0,
            buildings: zone.buildings || [],
            area: zone.zoneArea || zone.area || 0
          }
          
          // 确保颜色值有效
          if (!zoneData.color || zoneData.color === '#000000' || zoneData.color === 'black') {
            zoneData.color = getRandomColor()
          }
          
          return zoneData
        })
        console.log('分区数据加载完成，分区数量:', zones.value.length)
      }
      
      if (drawingData.placedBuildings && Array.isArray(drawingData.placedBuildings)) {
        placedBuildings.value = drawingData.placedBuildings
        console.log('已放置楼栋数据加载完成，楼栋数量:', placedBuildings.value.length)
        
        // 更新楼栋状态，将已放置的楼栋标记为已使用
        placedBuildings.value.forEach(building => {
          buildingStatus.value.set(building.id, 'used')
        })
        
        console.log('楼栋状态更新完成，已使用楼栋数量:', placedBuildings.value.length)
      }
      
      // 更新画布状态
      if (drawingData.canvasState) {
        canvasWidth.value = drawingData.canvasState.width || 800
        canvasHeight.value = drawingData.canvasState.height || 600
        zoomLevel.value = drawingData.canvasState.zoomLevel || 1
        isSelectMode.value = drawingData.canvasState.isSelectMode || false
      }
      
      // 重新绘制画布
      redrawCanvas()
      
      ElMessage.success('绘图数据加载成功')
    } else {
      console.log('暂无绘图数据')
      ElMessage.info('暂无绘图数据，可以开始创建新分区')
    }
    
  } catch (error) {
    console.error('加载绘图数据失败:', error)
    ElMessage.info('暂无绘图数据，可以开始创建新分区')
  }
}

// 为分区生成绘图数据
const generateZoneDrawingData = async (zone: any): Promise<Zone> => {
  try {
    console.log('为分区生成绘图数据:', zone)
    
    // 计算默认位置（避免与现有分区重叠）
    const gridSize = 120
    const cols = Math.floor(canvasWidth.value / gridSize)
    const existingZonesCount = zones.value.length
    const row = Math.floor(existingZonesCount / cols)
    const col = existingZonesCount % cols
    
    const defaultZone: Zone = {
      id: zone.id,
      name: zone.zoneName || zone.name || `分区${existingZonesCount + 1}`,
      zoneName: zone.zoneName,
      color: zone.zoneColor || zone.color || getRandomColor(),
      points: JSON.stringify([
        { x: col * gridSize + 60, y: row * gridSize + 60 },
        { x: col * gridSize + 180, y: row * gridSize + 60 },
        { x: col * gridSize + 180, y: row * gridSize + 180 },
        { x: col * gridSize + 60, y: row * gridSize + 180 }
      ]),
      textX: col * gridSize + 120,
      textY: row * gridSize + 120,
      buildings: zone.buildings || [],
      area: zone.zoneArea || zone.area || 0
    }
    
    // 确保颜色值有效
    if (!defaultZone.color || defaultZone.color === '#000000' || defaultZone.color === 'black') {
      defaultZone.color = getRandomColor()
    }
    
    console.log(`生成分区绘图数据: ${defaultZone.name} (ID: ${defaultZone.id}, 颜色: ${defaultZone.color})`)
    return defaultZone
  } catch (error) {
    console.error('生成分区绘图数据失败:', error)
    throw error
  }
}

// 同步分区列表与绘图区域
const syncZonesWithDrawing = async () => {
  try {
    console.log('开始同步分区列表与绘图区域...')
    
    // 获取当前绘图区域中的分区ID列表
    const drawingZoneIds = new Set(zones.value.map(zone => zone.id))
    console.log('绘图区域中的分区ID:', Array.from(drawingZoneIds))
    
    // 使用已保存的分区列表数据，避免重复调用API
    if (selectedCommunity.value && zoneListData.value.length > 0) {
      const zoneList = zoneListData.value
      console.log('原始分区列表数据:', zoneList)
      const zoneListIds = new Set(zoneList.map((zone: any) => zone.id))
      console.log('分区列表中的分区ID:', Array.from(zoneListIds))
      
      // 找出在分区列表中但不在绘图区域中的分区
      console.log('开始过滤缺失分区...')
      console.log('绘图区域中的分区ID集合:', drawingZoneIds)
      console.log('分区列表数据:', zoneList)
      
      const missingZones = zoneList.filter((zone: any) => {
        const isMissing = !drawingZoneIds.has(zone.id)
        console.log(`分区 ${zone.id} (${zone.zoneName || zone.name}): 是否缺失 = ${isMissing}`)
        return isMissing
      })
      console.log('需要添加到绘图区域的分区:', missingZones)
      
      if (missingZones.length > 0) {
        console.log(`发现${missingZones.length}个缺失的分区，开始生成绘图数据...`)
        
        // 为缺失的分区生成默认绘图数据
        const newZones = missingZones.map((zone: any, index: number) => {
          // 计算默认位置（避免重叠）
          const gridSize = 120
          const cols = Math.floor(canvasWidth.value / gridSize)
          const row = Math.floor(index / cols)
          const col = index % cols
          
          const defaultZone: Zone = {
            id: zone.id,
            name: zone.zoneName || zone.name || `分区${index + 1}`,
            zoneName: zone.zoneName,
            color: zone.zoneColor || zone.color || getRandomColor(),
            points: JSON.stringify([
              { x: col * gridSize + 60, y: row * gridSize + 60 },
              { x: col * gridSize + 180, y: row * gridSize + 60 },
              { x: col * gridSize + 180, y: row * gridSize + 180 },
              { x: col * gridSize + 60, y: row * gridSize + 180 }
            ]),
            textX: col * gridSize + 120,
            textY: row * gridSize + 120,
            buildings: zone.buildings || [],
            area: zone.zoneArea || zone.area || 0
          }
          
          // 确保颜色值有效
          if (!defaultZone.color || defaultZone.color === '#000000' || defaultZone.color === 'black') {
            defaultZone.color = getRandomColor()
          }
          
          console.log(`生成分区绘图数据: ${defaultZone.name} (ID: ${defaultZone.id}, 颜色: ${defaultZone.color})`)
          return defaultZone
        })
        
        // 将新分区添加到绘图区域
        zones.value.push(...newZones)
        console.log('成功添加分区到绘图区域，新增分区数量:', newZones.length)
        console.log('当前zones.value内容:', zones.value)
        
        ElMessage.success(`成功同步${newZones.length}个分区到绘图区域`)
             } else {
         console.log('分区列表与绘图区域已同步，无需添加新分区')
       }
     }
   } catch (error) {
    console.error('同步分区列表与绘图区域失败:', error)
    ElMessage.warning('同步分区数据时出现异常，但不影响正常使用')
  }
}



// 加载初始数据
const loadInitialData = async (communityId: number) => {
  try {
    console.log('开始加载初始数据，社区ID:', communityId)
    
    // 并行加载社区信息和楼栋列表
    await Promise.all([
      loadCommunityInfo(communityId),
      loadBuildingList(communityId)
    ])
    
    // 尝试加载绘图数据
    await loadDrawingData(communityId)
    
    // 无论是否有绘图数据，都执行分区同步
    console.log('准备执行分区同步...')
    await syncZonesWithDrawing()
    console.log('分区同步执行完成')
    
    // 在数据加载和同步完成后，统一重新绘制画布
    console.log('数据加载完成，开始绘制画布...')
    
    // 更新所有分区面积
    updateAllZoneAreas()
    
    // 更新所有楼栋的分区归属
    updateAllBuildingZoneAssignments()
    
    // 确保Canvas上下文已初始化后再绘制
    if (canvasRef.value && !ctx.value) {
      ctx.value = canvasRef.value.getContext('2d')
      console.log('Canvas上下文延迟初始化完成:', ctx.value)
      
      // 立即设置Canvas背景色，避免黑色显示
      if (ctx.value) {
        ctx.value.fillStyle = '#ffffff'
        ctx.value.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
      }
    }
    
    redrawCanvas()
    
  } catch (error) {
    console.error('加载初始数据失败:', error)
    ElMessage.error('加载初始数据失败')
  }
}


onMounted(async () => {
  // 初始化Canvas上下文（但不立即绘制，等待数据加载完成后再绘制）
  if (canvasRef.value) {
    ctx.value = canvasRef.value.getContext('2d')
    console.log('Canvas上下文初始化完成:', ctx.value)
    
    // 立即设置Canvas背景色，避免黑色显示
    if (ctx.value) {
      ctx.value.fillStyle = '#ffffff'
      ctx.value.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
    }
  }
  
  // 检查是否有从社区列表传递过来的参数
  const communityId = route.query.communityId
  const communityName = route.query.communityName
  const propertyCompanyId = route.query.propertyCompanyId
  
  if (communityId) {
    const communityIdNum = Number(communityId)
    selectedCommunity.value = communityIdNum
    
    // 执行社区进入状态判断逻辑
    await determineCommunityEntryState(communityIdNum)
    
    // 使用统一的初始数据接口加载所有数据
    await loadInitialData(communityIdNum)
    
    // 显示欢迎信息
    ElMessage.success(`欢迎进入${communityName || '社区'}的分区管理`)
  } else {
    ElMessage.warning('未指定社区，请从社区管理页面进入')
  }
  
  // 3秒后隐藏提示
  setTimeout(() => {
    showTips.value = false
  }, 3000)
})

// 获取分区中实际的楼栋数量
const getZoneBuildingCount = (zoneId: number): number => {
  // 从绘图区域中找到对应的分区
  const zoneInDrawing = zones.value.find(zone => zone.id === zoneId)
  if (zoneInDrawing) {
    return zoneInDrawing.buildings.length
  }
  return 0
}

// 更新所有楼栋的分区归属

// 跳转到楼栋管理页面
const goToBuildingManagement = () => {
  ElMessage.info('请先添加楼栋信息')
  // 这里可以添加跳转到楼栋管理页面的逻辑
  // router.push('/region/building')
}
</script>


<style scoped>

/* 社区信息栏样式 */
.community-info-bar {
  margin-bottom: 8px; /* 减少底部间距 */
}

.community-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
}

.community-card :deep(.el-card__body) {
  padding: 8px 20px; /* 减少上下内边距 */
}

.community-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: white;
  gap: 20px; /* 添加左右间距 */
}

.community-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  flex-shrink: 0; /* 防止压缩 */
}

.community-name .el-icon {
  font-size: 18px;
  color: #ffd700;
}

.name-text {
  color: white;
}

.community-address {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  font-size: 14px;
  flex: 1;
}

.address-details {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
  flex-wrap: wrap;
}

.region-path {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 2px;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.9);
}

.region-item {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.region-separator {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
  margin: 0 2px;
}

.detail-address {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
}

.operation-mode-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  margin-left: auto;
}

.operation-mode-indicator .el-tag {
  font-weight: 600;
  padding: 6px 12px;
}

.mode-description {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  text-align: center;
}

.address-text {
  color: rgba(255, 255, 255, 0.9);
  flex: 1; /* 占用剩余空间 */
  min-width: 0; /* 允许文本截断 */
}

.community-address .el-icon {
  font-size: 16px;
  color: #87ceeb;
  flex-shrink: 0; /* 防止图标压缩 */
}

.address-text {
  color: rgba(255, 255, 255, 0.9);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap; /* 防止换行 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .community-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px; /* 减少垂直间距 */
  }
  
  .community-name,
  .community-address {
    font-size: 14px;
  }
  
  .community-card :deep(.el-card__body) {
    padding: 6px 16px; /* 进一步减少内边距 */
  }
}

/* 分区管理容器 */
.zone-management-container {
  padding: 20px;
  height: 100vh;
  background-color: #f5f7fa;
  overflow: hidden;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-title .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.page-description {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.card-header .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.zone-management-main {
  margin-top: 24px;
}

.zone-layout {
  display: grid;
  grid-template-columns: 260px 1fr 300px;
  gap: 16px;
  height: calc(100vh - 200px);
}

.building-library {
  height: 100%;
}

.library-card {
  height: 100%;
  border-radius: 8px;
}

.library-content {
  height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
}



.building-list {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.building-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.building-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.building-selected {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.building-icon {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #409eff;
  color: white;
  border-radius: 4px;
  margin-right: 12px;
}

.building-info {
  flex: 1;
}

.building-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.building-type {
  font-size: 12px;
  color: #909399;
}

.drawing-area {
  height: 100%;
}

.drawing-card {
  height: 100%;
  border-radius: 8px;
}

.drawing-card .card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
}

.tool-group {
  display: flex;
  gap: 8px;
}

.zoom-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.zoom-group {
  display: flex;
  align-items: center;
  gap: 4px;
}

.zoom-label {
  font-size: 12px;
  color: #606266;
  margin-right: 4px;
}

.zoom-level {
  min-width: 50px;
  text-align: center;
  font-size: 12px;
  color: #606266;
}

.canvas-container {
  height: calc(100% - 60px);
  overflow: auto;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafafa;
  position: relative; /* Added for positioning canvas and tips */
}

.drawing-canvas {
  display: block;
  cursor: crosshair;
  background-color: #ffffff;
}

.canvas-tips {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  max-width: 250px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.tip-content {
  font-size: 12px;
  color: #606266;
}

.tip-content p {
  margin: 0 0 8px 0;
  font-weight: 600;
  color: #303133;
}

.tip-content ul {
  margin: 0;
  padding-left: 16px;
}

.tip-content li {
  margin-bottom: 4px;
  line-height: 1.4;
}

.grid-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: 
    linear-gradient(rgba(0,0,0,0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0,0,0,0.1) 1px, transparent 1px);
  background-size: 20px 20px;
}

.placed-building {
  position: absolute;
  cursor: move;
  transition: all 0.3s;
  user-select: none;
}

.placed-building:hover {
  /* 移除悬停放大效果，保持普通拖拽 */
}

.placed-building.building-selected {
  z-index: 10;
}

.building-actions {
  position: absolute;
  top: -8px;
  right: -8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.placed-building:hover .building-actions {
  opacity: 1;
}

.building-delete-btn {
  width: 20px;
  height: 20px;
  font-size: 10px;
  padding: 0;
}

.placed-building .building-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #409eff;
  color: white;
  border-radius: 6px;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
}

.placed-building .building-icon:hover {
  background-color: #337ecc;
}

.building-text {
  position: absolute;
  bottom: 2px;
  left: 2px;
  right: 2px;
  font-size: 10px;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: white;
  font-weight: 500;
  line-height: 1;
}

.zone-lines {
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none;
}

.zone-panel {
  height: 100%;
}

.panel-card {
  height: 100%;
  border-radius: 8px;
}

.panel-content {
  height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
}

.zone-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
}

.zone-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.zone-item:hover {
  border-color: #409eff;
}

.zone-active {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.zone-color {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  margin-right: 12px;
}

.zone-info {
  flex: 1;
}

.zone-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.zone-buildings {
  font-size: 12px;
  color: #909399;
}

.zone-actions {
  display: flex;
  gap: 4px;
}

.zone-edit-form {
  margin-bottom: 16px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafafa;
}

.no-buildings {
  color: #909399;
  font-style: italic;
  font-size: 12px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.building-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.create-zone {
  margin-top: auto;
  text-align: center;
}

.canvas-tips {
  position: absolute;
  top: 20px; /* Adjust as needed */
  left: 20px; /* Adjust as needed */
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 15px;
  border-radius: 8px;
  font-size: 14px;
  z-index: 10;
  max-width: 300px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.tip-content {
  line-height: 1.6;
}

.tip-content p {
  margin-bottom: 8px;
  font-weight: bold;
}

.tip-content ul {
  padding-left: 20px;
}

.tip-content li {
  margin-bottom: 4px;
}

.no-buildings {
  color: #909399;
  font-style: italic;
}

/* 分区状态样式 */
.zone-not-in-drawing {
  opacity: 0.7;
  border: 1px dashed #e6a23c;
}

.zone-not-in-drawing:hover {
  opacity: 1;
  border: 1px solid #e6a23c;
}

.zone-status-tag {
  margin-left: 8px;
  font-size: 10px;
  padding: 2px 6px;
}

/* 无绘图数据提示样式 */
.no-drawing-data {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 400px;
  background-color: #f8f9fa;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
}

.no-data-content {
  text-align: center;
  padding: 40px;
}

.no-data-icon {
  font-size: 64px;
  color: #d1d5db;
  margin-bottom: 16px;
}

.no-data-content h3 {
  color: #6b7280;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
}

.no-data-content p {
  color: #9ca3af;
  font-size: 14px;
  margin-bottom: 24px;
  line-height: 1.5;
}

.no-data-content .el-button {
  padding: 12px 24px;
  font-size: 14px;
}

@media (max-width: 1200px) {
  .zone-layout {
    grid-template-columns: 250px 1fr 280px;
  }
}

@media (max-width: 768px) {
  .zone-layout {
    grid-template-columns: 1fr;
    grid-template-rows: auto 1fr auto;
  }
  
  .selection-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .selection-item {
    min-width: auto;
  }
}

/* 删除对话框样式 */
:deep(.delete-building-dialog) {
  .el-message-box__header {
    background: #fef0f0;
    border-bottom: 1px solid #fde2e2;
  }
  
  .el-message-box__title {
    color: #e74c3c;
    font-weight: bold;
  }
  
  .el-message-box__content {
    padding: 20px;
  }
  
  .el-button--primary {
    background: #e74c3c;
    border-color: #e74c3c;
  }
  
  .el-button--primary:hover {
    background: #c0392b;
    border-color: #c0392b;
  }
}

</style>
